package com.educhains.web.ctrl.frontend;

import com.educhains.module.certification.service.CourseCertificationService;
import com.educhains.module.certification.vo.CourseCertification;
import com.educhains.module.course.vo.Course;
import com.educhains.module.user.service.UserService;
import com.educhains.module.user.vo.User;
import com.educhains.web.util.FileHashUtils;
import com.educhains.web.util.PropertyUtils;
import org.apache.commons.io.FileUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/certification")
public class CertificationCtrl {

    @Autowired
    CourseCertificationService courseCertificationService = null;

    @Autowired
    UserService userService = null;


    /**
     * 测试页面跳转
     *
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return "frontend/certification/courseCertification";
    }


    @RequestMapping("/show/{fileHash}")
    @ResponseBody
    public String showCertification(HttpServletRequest request, @PathVariable String fileHash) throws JSONException {

        CourseCertification certification = this.courseCertificationService.getCertificationByFileHash(fileHash);

        JSONObject jsonObject = new JSONObject();

        if (certification != null) {
            String filePath = certification.getCertificationFilePath();
            jsonObject.put("filePath", filePath);
            jsonObject.put("msg", "success");
            return jsonObject.toString();
        } else {
            jsonObject.put("msg", "error");
            return jsonObject.toString();
        }
    }


    @RequestMapping("/list/{userId}")
    public String getCertificationList(HttpServletRequest request, @PathVariable("userId") String userId) {
        List<CourseCertification> certificationList = this.courseCertificationService.getCertificationByUserId(userId);

        List<Course> courseList = new ArrayList<Course>();
        for (CourseCertification certification : certificationList) {
            int courseId = certification.getCertificationCourseId();
            // TODO 根据课程ID获取课程信息
        }

        request.setAttribute("certificationList", certificationList);
        return "frontend/certification/userFile";
    }


    @RequestMapping("/list/{courseId}")
    public String getCertificationList(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        List<CourseCertification> certificationList = this.courseCertificationService.getCertificationByCourseId(Integer.valueOf(courseId));

        // 根据课程id获取用户id，进而获取到学生的信息
        List<User> userList = new ArrayList<User>();
        for (CourseCertification certification : certificationList) {
            String userId = certification.getCertificationUserId();
            User user = this.userService.selectUserById(userId);
            userList.add(user);
        }

        request.setAttribute("certificationList", certificationList);
        request.setAttribute("userList", userList);
        return "frontend/certification/userFile";
    }


    @RequestMapping("/certify")
    @ResponseBody
    public String certify(HttpServletRequest request) {
        CourseCertification certification = new CourseCertification();
        certification.setCertificationFileHash(request.getParameter("fileHash"));
        certification.setCertificationFilePath(request.getParameter("fileName"));
        certification.setCertificationCourseId(Integer.valueOf(request.getParameter("courseId")));
        certification.setCertificationUserId(request.getParameter("userId"));

        if (this.courseCertificationService.certify(certification) == 1) {
            return "success";
        } else {
            return "error";
        }

    }

    /**
     * 上传文件操作
     *
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/check")
    @ResponseBody
    public String check(MultipartFile file) throws Exception {

        String fileName = file.getOriginalFilename();
        String path = PropertyUtils.getProperty("file.index");
        String filePath = path + "\\" + fileName;

        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //MultipartFile自带的解析方法
        file.transferTo(dir);


        String md5 = fileVerify(filePath);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileName", fileName);
        jsonObject.put("fileHash", md5);


        return jsonObject.toString();
    }

    /**
     * 获取文件MD5码
     *
     * @param filename
     * @return
     * @throws Exception
     */
    private String fileVerify(String filename) throws Exception {
        return FileHashUtils.getMD5HashCode(filename);
    }

    /**
     * spring mvc 下载文件操作
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/download")
    public ResponseEntity<byte[]> downloadCertification(HttpServletRequest request) throws IOException {
        String fileName = request.getParameter("path");
        String path = PropertyUtils.getProperty("file.index");
        File file = new File(path + "\\" + fileName);
        HttpHeaders headers = new HttpHeaders();

        // 下载显示的文件名，解决中文乱码问题
        String fileName_1 = new String(file.getName().getBytes("UTF-8"), "iso-8859-1");
        // 通知浏览器以attachment(下载方式)打开文件
        headers.setContentDispositionFormData("attachment", fileName_1);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }

}
